package com.axones.planningpoker.dao;

import com.axones.planningpoker.bean.Project;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class ProjectDAO {
	private static final String KIND_NAME = "Project";

	/**
	 * @param project
	 */
	public Long add(Project project) {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		return datastore.put(convert(project)).getId();
	}

	/**
	 * @param projectId
	 * @return
	 */
	public Project get(long projectId) {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Key k = KeyFactory.createKey(KIND_NAME, projectId);

		try {
			return convert(datastore.get(k));
		} catch (EntityNotFoundException e) {
			return null;
		}
	}

	/**
	 * @param project
	 */
	public void delete(Long id) {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Key k = KeyFactory.createKey(KIND_NAME, id);

		datastore.delete(k);
	}

	/**
	 * @param project
	 * @return
	 */
	public String update(Project project) {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Key k = KeyFactory.createKey(KIND_NAME, project.getId());

		Entity p;

		try {
			p = datastore.get(k);
		} catch (EntityNotFoundException e) {
			return "not.found";
		}

		update(project, p);

		datastore.put(p);

		return "ok";
	}

	/**
	 * @param p
	 * @return
	 */
	private Project convert(Entity p) {
		Project project = new Project();

		project.setId(p.getKey().getId());

		project.setName((String) p.getProperty("name"));

		return project;
	}

	/**
	 * @param project
	 * @return
	 */
	private Entity convert(Project project) {
		Entity p = new Entity(KIND_NAME);

		p.setProperty("name", project.getName());

		return p;
	}

	/**
	 * @param project
	 * @param p
	 */
	private void update(Project project, Entity p) {
		p.setProperty("name", project.getName());
	}
}
